package test2;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import javax.sound.midi.Soundbank;
import javax.xml.parsers.FactoryConfigurationError;
import java.io.EOFException;
import java.util.Set;

/**
 * 服务端
 */
public class Server {
    public static final String HOST = "tcp://wblink.tpddns.cn:8083";
    public static final String TOPIC = "test";
    public static final String CLIENTID = "mqtt111";

    private MqttClient client;
    private MqttTopic topic;
    private String username = "admin";
    private String password = "public";
    private MqttMessage message;

    public Server(){
        try {
            client = new MqttClient(HOST,CLIENTID, new MemoryPersistence());
            connect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    private void connect(){
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        options.setConnectionTimeout(10);
        options.setKeepAliveInterval(60);
        try {
            client.setCallback(new PushCallback());
            System.out.println("options = " + options);
            System.out.println("client: " + client);
            client.connect(options);

            topic = client.getTopic(TOPIC);
        } catch (MqttException e) {
            e.printStackTrace();
            System.out.println("MqttException");
        }

    }

    public void publish(MqttTopic topic,MqttMessage message) throws MqttPersistenceException,MqttException{
        MqttDeliveryToken token = topic.publish(message);
        token.waitForCompletion();
        System.out.println("消息已发布" + token.isComplete());
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.message = new MqttMessage();
        server.message.setQos(2);
        server.message.setRetained(true);
        server.message.setPayload("hello world".getBytes());
        try {
            server.publish(server.topic, server.message);
        } catch (MqttException e) {
            e.printStackTrace();
        }
        System.out.println(server.message.isRetained() + "....isRetained状态" );
    }
}
